//
//  MediaView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/29/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit

protocol MediaViewProtocol {
    func removeImage (at index: Int)
}

final class MediaView: UIView {
    
    // MARK: - UIView
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 5
        return imageView
    }()
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "close"), for: .normal)
        return btn
    }()
    
    // MARK: - Properties
    
    var delegate: MediaViewProtocol!
    private var index: Int!
    
    // MARK: - Actions
    
    @objc func onRemoveImage(sender: UIButton) {
        delegate.removeImage(at: index)
    }
    
    // MARK: - Init
    
    public func putData (image: UIImage, index: Int) {
        self.index = index
        self.addViews(image: image)
    }
    
    public func updateIndex (index: Int) {
        self.index = index
    }
    
    // MARK: - UI
    
    private func addViews (image: UIImage) {
        self.addSubview(imageView)
        self.addSubview(closeBtn)
        self.clipsToBounds = true
        
        closeBtn.addTarget(self, action: #selector(onRemoveImage(sender:)), for: .touchUpInside)
        
        snp.makeConstraints { (make) in
            make.width.height.equalTo(91.0)
        }
        imageView.snp.makeConstraints { (make) in
            make.bottom.leading.equalToSuperview()
            make.width.height.equalTo(80.0)
        }
        closeBtn.snp.makeConstraints { (make) in
            make.trailing.top.equalToSuperview()
            make.width.height.equalTo(22)
        }
        
        imageView.image = image
    }
}
